import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { List, Skeleton, message, Modal } from 'antd'
import moment from 'moment'
import { MoreOutlined, FileTextOutlined, FileDoneOutlined, UserOutlined, BellOutlined } from '@ant-design/icons'
// import Calendar from '@components/Calendar'
import style from './SendDesktop.module.less'
import { updateUncompleteMessage } from '@redux/actions'

class SendDesktop extends Component {
  state = {
    toReceiveNumber: 0,
    toReceiveNumberLoading: false,
    sendedNumber: 0,
    sendedNumberLoading: false,
    unsendNumber: 0,
    unsendNumberLoading: false,
    postponeNumber: 0,
    postponeNumberLoading: false
  }

  formatDate (date) {
    if (!date) { return date }
    return moment(date * 1000).format('YYYY-MM-DD HH:mm')
  }

  toDealHandle (d) {
    this.setState({ messageListvisible: false })
    let route = d.route ? d.route : null
    if (!route) {
      return message.warning('处理地址不存在')
    }
    try {
      route = JSON.parse(route)
    } catch (e) {
      return message.warning('获取处理地址错误')
    }
    const component = route.component || route.type
    if (component === 'caseDetail') {
      const { id, operate } = route.meta
      this.props.addWindow({ id: `CaseDetail-${id}`, title: `案件详情-${route.title}`, componentName: 'CaseDetail', forceRefresh: false, meta: { id, operate, editable: true } })
    }
    this.setMessageReaded(d.read_datetime, d.id)
  }

  // 设置未读信息未已读
  setMessageReaded (time, id) {
    if (time) { return false }
    this.$put(`/api/xapc/message/read/${id}`)
      .then(res => {
        if (res.status === 1) {
          this.props.updateUncompleteMessage()
        } else {
          message.warning(res.message)
        }
      })
  }

  openMessageList () {
    this.setState({ messageListvisible: false })
    this.props.addWindow({ id: 'MessageList', title: '消息列表', componentName: 'MessageList' })
  }

  // 获取待接收
  getToReceiveNumber () {
    this.setState({ toReceiveNumberLoading: true })
    return this.$get('/api/xapc/case/unreceive', {
      condition: JSON.stringify([]),
      conly: true
    }).then(res => {
      this.setState({ toReceiveNumberLoading: false })
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      this.setState({
        toReceiveNumber: res.data
      })
    }).catch(() => this.setState({ toReceiveNumberLoading: false }))
  }

  // 获取已送案件
  getSendedNumber () {
    this.setState({ sendedNumberLoading: true })
    return this.$get('/api/xapc/case', {
      condition: JSON.stringify([{ k: 'status', o: 'in', v: '送达完成' }]),
      conly: true
    }).then(res => {
      this.setState({ sendedNumberLoading: false })
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      this.setState({
        sendedNumber: res.data
      })
    }).catch(() => this.setState({ sendedNumberLoading: false }))
  }

  // 获取未送案件
  getUnsendNumber () {
    this.setState({ unsendNumberLoading: true })
    return this.$get('/api/xapc/case', {
      condition: JSON.stringify([{ k: 'status', o: '=', v: '移交送达' }]),
      conly: true
    }).then(res => {
      this.setState({ unsendNumberLoading: false })
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      this.setState({
        unsendNumber: res.data
      })
    }).catch(() => this.setState({ unsendNumberLoading: false }))
  }

  // 获取暂缓数量
  getPostponeNumber () {
    return Promise.resolve(0)
  }

  // 获取统计数据
  getStatistics () {
    this.getToReceiveNumber()
    this.getSendedNumber()
    this.getUnsendNumber()
    this.getPostponeNumber()
  }

  // 前往待接收
  gotoReceive () {
    this.props.addWindow({ id: 'UnreceiveCaseManage', title: '待接收案件', componentName: 'UnreceiveCaseManage', forceRefresh: true, meta: { } })
  }

  // 前往已送案件
  gotoSended () {
    this.props.addWindow({ id: 'SendCaseManage', title: '送达案件', componentName: 'SendCaseManage', forceRefresh: true, meta: { status: '送达完成' } })
  }

  // 前往未送案件
  gotoUnsend () {
    this.props.addWindow({ id: 'SendCaseManage', title: '送达案件', componentName: 'SendCaseManage', forceRefresh: true, meta: { status: '移交送达' } })
  }

  gotoPostpone () {
    Modal.info({
      title: '暂未暂缓送达',
      onOk () {}
    })
  }

  componentDidMount () {
    this.getStatistics()
  }

  // 渲染提醒块
  renderNoticeItem (title, numKey, icon, activeStyle, handle = () => {}) {
    if (this.state[`${numKey}Loading`]) {
      return (
        <div className={style['header-block']}>
          <Skeleton active />
        </div>
      )
    }
    const blockStyle = [style['header-block']]
    const num = this.state[numKey]
    if (num > 0) {
      blockStyle.push(activeStyle)
    }
    return (
      <div className={blockStyle.join(' ')} onClick={() => handle()}>
        <div className={style['icon-box']}>
          {icon}
        </div>
        <div className={style['header-block-text']}>
          <div className={style['header-block__text--top']}>{title}</div>
          <div className={style['header-block__text--bottom']}>
            <span className={style['header-block__text-num']}>{num}</span>
            <span className={style['header-block__text-unit']}>件</span>
          </div>
        </div>
      </div>
    )
  }

  // 渲染提示列表
  renderNoticeItemList () {
    return (
      <>
        {this.renderNoticeItem('待接收', 'toReceiveNumber', <FileTextOutlined />, style.active, () => this.gotoReceive())}
        {this.renderNoticeItem('已送案件', 'sendedNumber', <UserOutlined />, style.active, () => this.gotoSended())}
        {this.renderNoticeItem('未送案件', 'unsendNumber', <FileDoneOutlined />, style.active, () => this.gotoUnsend())}
        {this.renderNoticeItem('暂缓送达', 'postponeNumber', <BellOutlined />, style.active, () => this.gotoPostpone())}
      </>
    )
  }

  // 渲染消息标题
  renderMessageTitle (item, i) {
    return (
      <span className={style['item-name']} onClick={() => this.toDealHandle(item)}>
        <span>{i + 1}、{item.title}</span>
        {item.level ? <span className={style['item-urgency']}>紧急</span> : null}
      </span>
    )
  }

  render () {
    return (
      <div className={style.container}>{/*  */}
        <div className={style.header}>
          <div className={style['header-inner']}>
            {this.renderNoticeItemList()}
          </div>
        </div>
        <div className={style.body}>
          <div className={style['body-left']}>
            <div className={style['body-title-line']}>
              <span className={style['body-title__text']}>提醒通知</span>
              <span className={style['body__more-btn']} onClick={() => this.openMessageList()}>
                <MoreOutlined rotate='90' />
              </span>
            </div>

            <div>
              <List
                itemLayout='horizontal' dataSource={this.props.uncompleteMessageList} pagination={false} renderItem={(item, i) => {
                  return (
                    <List.Item>
                      <Skeleton avatar title={false} loading={item.loading} active>
                        <List.Item.Meta
                          title={this.renderMessageTitle(item, i)}
                          description={item.content}
                        />
                        <span>{this.formatDate(item.create_datetime)}</span>
                      </Skeleton>
                    </List.Item>
                  )
                }}
              />
            </div>

            {/* <ul className={style['notice-list']}>
              <li>
                <div className={style['notice-icon']}>
                  <Badge status='error' dot offset={[-2, 2]}>
                    <img src={require('../../assets/img/case-status-1.jpg')} alt='status' />
                  </Badge>
                </div>
                <div className={style['title-line']}>
                  <a href='123'>减免收费审批</a>
                </div>
                <div className={style['text-line']}>
                  <span>20191268减免交费审批通过，请及时通知当事人交费...</span>
                  <span>2020-10-01 12:00</span>
                </div>
              </li>

              <li>
                <div className={style['notice-icon']}>
                  <Badge status='error' dot offset={[-2, 2]}>
                    <img src={require('../../assets/img/case-status-2.jpg')} alt='status' />
                  </Badge>
                </div>
                <div className={style['title-line']}>
                  <a href='123'>秘书呈批结果</a>
                </div>
                <div className={style['text-line']}>
                  <span>20191268已指定某某秘书，生成案号XA2020001，请及时处理...</span>
                  <span>2020-10-01 12:00</span>
                </div>
              </li>

              <li>
                <div className={style['notice-icon']}>
                  <Badge status='error' dot offset={[-2, 2]}>
                    <img src={require('../../assets/img/case-status-3.jpg')} alt='status' />
                  </Badge>
                </div>
                <div className={style['title-line']}>
                  <a href='123'>保全呈批结果</a>
                </div>
                <div className={style['text-line']}>
                  <span>XA2020001财产保全审批通过，请及时处理...</span>
                  <span>2020-10-01 12:00</span>
                </div>
              </li>

              <li>
                <div className={style['notice-icon']}>
                  <Badge status='error' dot offset={[-2, 2]}>
                    <img src={require('../../assets/img/case-status-1.jpg')} alt='status' />
                  </Badge>
                </div>
                <div className={style['title-line']}>
                  <a href='123'>减免收费审批</a>
                </div>
                <div className={style['text-line']}>
                  <span>20191268减免交费审批通过，请及时通知当事人交费...</span>
                  <span>2020-10-01 12:00</span>
                </div>
              </li>

              <li>
                <div className={style['notice-icon']}>
                  <Badge status='error' dot offset={[-2, 2]}>
                    <img src={require('../../assets/img/case-status-2.jpg')} alt='status' />
                  </Badge>
                </div>
                <div className={style['title-line']}>
                  <a href='123'>秘书呈批结果</a>
                </div>
                <div className={style['text-line']}>
                  <span>20191268已指定某某秘书，生成案号XA2020001，请及时处理...</span>
                  <span>2020-10-01 12:00</span>
                </div>
              </li>
            </ul> */}
          </div>
          {/* <div className={style['body-right']}>
            <Calendar changeHandle={s => console.log(s)} tagList={['2020-04-01', '2020-04-21']} />
            <ul className={style['book-list']}>
              <li>
                <span className={style['book-li__time']}>14:00</span>
                <span>XA2020001案件在仲裁一厅开庭，仲裁员某某某</span>
              </li>
              <li>
                <span className={style['book-li__time']}>15:00</span>
                <span>XA2020001案件在仲裁一厅开庭，仲裁员某某某</span>
              </li>
              <li>
                <span className={style['book-li__time']}>16:00</span>
                <span>XA2020001案件在仲裁一厅开庭，仲裁员某某某</span>
              </li>
            </ul>
          </div> */}
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo,
    uncompleteMessageList: state.basic.uncompleteMessageList
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    updateUncompleteMessage: () => dispatch(updateUncompleteMessage(dispatch))
  }
})

export default connect(mapState, mapDispatch)(SendDesktop)
